package com.cssy.xxkj.logic.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.contants.BillTypeConstant;
import com.cssy.xxkj.logic.dao.LogicPurchaseReturnDAO;
import com.cssy.xxkj.logic.dao.LogicPurchaseReturnItemDAO;
import com.cssy.xxkj.logic.dao.LogicPurchaseWareDAO;
import com.cssy.xxkj.logic.dao.LogicPurchaseWareItemDAO;
import com.cssy.xxkj.logic.entity.LogicPurchaseReturnDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseReturnItemDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseWareDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseWareItemDO;
import com.cssy.xxkj.logic.service.ILogicHsUtilService;
import com.cssy.xxkj.logic.service.ILogicPurchaseReturnService;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtils;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.impl.SyCodeService;

@Service("logicPurchaseReturnService")
public class LogicPurchaseReturnServiceImpl implements
		ILogicPurchaseReturnService {
	
	@Resource(name = "logicPurchaseWareDAO")
	private LogicPurchaseWareDAO logicPurchaseWareDAO;
	
	@Resource(name = "logicPurchaseWareItemDAO")
	private LogicPurchaseWareItemDAO logicPurchaseWareItemDAO;

	@Resource(name = "logicPurchaseReturnDAO")
	private LogicPurchaseReturnDAO logicPurchaseReturnDAO;
	
	@Resource(name = "logicPurchaseReturnItemDAO")
	private LogicPurchaseReturnItemDAO logicPurchaseReturnItemDAO;
	
	@Resource(name = "logicHsUtilService")
	private ILogicHsUtilService logicHsUtilService;
	
	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;
	
	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs=new SearchResult(scs);
		List<LogicPurchaseReturnDO> list = logicPurchaseReturnDAO.find(scs);
		rs.setRecordCount(logicPurchaseReturnDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		return logicPurchaseReturnDAO.deleteLogicPurchaseReturnDOByPrimaryKey(id);
	}

	@Override
	public Integer update(LogicPurchaseReturnDO pcsReturn, User user)
			throws SyBaseException {
		pcsReturn.setBizModifyName(user.getName());
		pcsReturn.setBizModifyDate(new Date());
		pcsReturn.setBizVersionMark(pcsReturn.getBizVersion());
		pcsReturn.setBizVersion(pcsReturn.getBizVersion()+Integer.valueOf(1));
		return logicPurchaseReturnDAO.updateLogicPurchaseReturnDO(pcsReturn);
	}

	@Override
	public LogicPurchaseReturnDO save(LogicPurchaseReturnDO pcsReturn, User user)
			throws SyBaseException {
		pcsReturn.setBizVersion(Integer.valueOf(1));
		pcsReturn.setBizCreatorName(user.getName());
		pcsReturn.setBizCreatorDate(new Date());
		logicPurchaseReturnDAO.insertLogicPurchaseReturnDO(pcsReturn);
		return pcsReturn;
	}
	
	@Override
	public void purchaseReturnSave(LogicPurchaseReturnDO curAP, HttpServletRequest request)
			throws SyBaseException{
		String flagMark = request.getParameter("flagMark");
		String zd011BackDate = request.getParameter("zd011BackDate");
		String itemdata = request.getParameter("itemdata");
		String itemdele = request.getParameter("itemdele"); 
		if(StringUtils.isBlank(zd011BackDate)){
			curAP.setZd011BackDate(new Date());
		}else{
			curAP.setZd011BackDate(DateUtils.stringToDate(zd011BackDate));
		}
		try{
			curAP.setZd006PayStatus(BillStatusUtil.PCSR_PAY_BILL_STATUS_ONE);
			if(BillStatusUtil.PCSR_BILL_STATUS_FIVE.equals(flagMark)){
				//驳回
				if(curAP==null || StringUtils.isBlank(curAP.getId())){
					throw new SyBaseException("数据错误，请重新操作！");
				}
				LogicPurchaseReturnDO pcsReturnDO = logicPurchaseReturnDAO.findLogicPurchaseReturnDOByPrimaryKey(curAP.getId());
				pcsReturnDO.setZd006Status(flagMark);
				this.update(pcsReturnDO, SessionUtil.getUser(request));
			}else{
				
				List<LogicPurchaseReturnItemDO> pcsrmList = JSONArray.parseArray(itemdata,LogicPurchaseReturnItemDO.class);
				if(curAP==null || StringUtils.isBlank(curAP.getId())){
					//新增
					String pcsrId = IDCodeTypeUtil.getId();
					curAP.setId(pcsrId);
					curAP.setZd003Code(syCodeService.getCode(BillTypeConstant.PURCHASERETURN,BillTypeConstant.PURCHASERETURN,SyCode.DATE_YYMM,5));
					curAP.setBizVersion(Integer.valueOf(1));
					curAP.setZd006Status(flagMark);
					this.save(curAP, SessionUtil.getUser(request));
					//增加行记录
					this.pcsrItemAddOrUp(pcsrmList, pcsrId, false);
				}else{
					//修改
					this.pcsrItemToRemove(itemdele);//删除的行记录信息
					if(BillStatusUtil.PCSR_BILL_STATUS_FOUR.equals(flagMark)){
						LogicPurchaseReturnDO pcsr = logicPurchaseReturnDAO.findLogicPurchaseReturnDOByPrimaryKey(curAP.getId());
						if(pcsr==null){
							throw new SyBaseException("数据发生改变，请重新提交");
						}
						//修改库存
						String pcswId = pcsr.getZd002PcsmId();//采购入库单id
						Map<String, BigDecimal> hasRnMap = this.findQueryPcsrItemToMap(pcswId);
						LogicPurchaseWareDO pcsw = logicPurchaseWareDAO.findLogicPurchaseWareDOByPrimaryKey(pcswId);
						Map<String, LogicPurchaseWareItemDO> pcswmItemMap = this.findQuerayPcswmToMap(pcswId);
						//循环退货单的item
						for(LogicPurchaseReturnItemDO pcsrm : pcsrmList){
							if(pcsrm==null){
								continue;
							}
							String keyStr = pcswId+"_"+pcsrm.getZd003MaterId()+"_"+pcsrm.getZd008MaterModel()+"_"
								+pcsrm.getZd012MaterSize()+"_"+pcsrm.getZd010MaterColor()+"_"+pcsrm.getZd011MaterQuality();
							//总数，可以退总数=总入库数
							BigDecimal sumQuantity = pcsrm.getZd018InQuantiy()==null?BigDecimal.ZERO:pcsrm.getZd018InQuantiy();
							//本次退货数量
							BigDecimal theQuantity = pcsrm.getZd020BackQuantity()==null?BigDecimal.ZERO:pcsrm.getZd020BackQuantity();
							//已退货数量
							BigDecimal hasBackQuantity = BigDecimal.ZERO;
							if(hasRnMap==null||hasRnMap.get(keyStr)==null){
								hasBackQuantity = BigDecimal.ZERO;
							}else{
								hasBackQuantity = hasRnMap.get(keyStr);
							}
							//总数-(已退货数量+本次退货数量)
							BigDecimal comQuantity = sumQuantity.subtract(hasBackQuantity.add(theQuantity));
							int rowComp = BigDecimal.ZERO.compareTo(comQuantity);
							if(rowComp==1){
								throw new SyBaseException("退货数量已大于入库的数量。");
							}else{
								LogicPurchaseWareItemDO pcswm = pcswmItemMap.get(keyStr);
								if(pcswm==null){
									throw new SyBaseException("没有找到物料："+pcsrm.getZd005MaterName());
								}else{
									//已退货数量
									BigDecimal backQuantity = pcswm.getZd020BackQuantity()==null?BigDecimal.ZERO:pcswm.getZd020BackQuantity();
									pcswm.setZd020BackQuantity(backQuantity.add(theQuantity));
									pcswmItemMap.put(keyStr, pcswm);
									logicPurchaseWareItemDAO.updateLogicPurchaseWareItemDO(pcswm);
								}
							}
							boolean upSt = true;
							for(LogicPurchaseWareItemDO pcswmItem : pcswmItemMap.values()){
								if(pcswmItem==null){
									continue;
								}
								//入库数量
								BigDecimal inQuantity = pcswmItem.getZd018HsQuantity()==null?BigDecimal.ZERO:pcswmItem.getZd018HsQuantity();
								//已退货数量
								BigDecimal backQuantity = pcswmItem.getZd020BackQuantity()==null?BigDecimal.ZERO:pcswmItem.getZd020BackQuantity();
								BigDecimal upQuantity = inQuantity.subtract(backQuantity);
								int canUpSt = BigDecimal.ZERO.compareTo(upQuantity);
								if(canUpSt==-1){
									upSt = false;
								}
							}
							if(upSt){
								pcsw.setZd004WhStatus(BillStatusUtil.PCSW_WH_BILL_STATUS_THR);
							}else{
								pcsw.setZd004WhStatus(BillStatusUtil.PCSW_WH_BILL_STATUS_THR);
							}
							pcsw.setBizVersionMark(pcsw.getBizVersion());
							logicPurchaseWareDAO.updateLogicPurchaseWareDO(pcsw);
							//修改库存
							logicHsUtilService.processHsPurhcaseReturnItem(curAP, pcsrm, SessionUtil.getUser(request));
						}
						//更新退回记录
						pcsr.setZd006Status(flagMark);
						Integer rowUp = this.update(pcsr, SessionUtil.getUser(request));
						if(rowUp==null || rowUp.intValue()==0){
							throw new SyBaseException("数据发生改变，请重新提交。");
						}
					}else{
						curAP.setZd006Status(flagMark);
						Integer rowUp = this.update(curAP, SessionUtil.getUser(request));
						if(rowUp==null || rowUp.intValue()==0){
							throw new SyBaseException("数据发生改变，请重新提交。");
						}
						this.pcsrItemAddOrUp(pcsrmList, curAP.getId(), true);
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()+ e.getMessage());
		}
	}
	
	/**
	 * 删除采购入退货单的行记录
	 * @param pcswRelStr
	 * @throws SyBaseException
	 */
	private void pcsrItemToRemove(String pcsrRelStr)throws SyBaseException{
		if(StringUtils.isNotBlank(pcsrRelStr)){
			List<LogicPurchaseReturnItemDO> pcsrmList = JSONArray.parseArray(pcsrRelStr,LogicPurchaseReturnItemDO.class);
			for(LogicPurchaseReturnItemDO pcsrm : pcsrmList){
				if(pcsrm==null || StringUtils.isBlank(pcsrm.getId())){
					continue;
				}
				logicPurchaseReturnItemDAO.deleteLogicPurchaseReturnItemDOByPrimaryKey(pcsrm.getId());
			}
		}
	}
	
	/**
	 * 新增或者删除采购退货的行记录信息
	 * @param pcswmList
	 * @param pcswId
	 * @param addOrUp
	 * @throws SyBaseException
	 */
	private void pcsrItemAddOrUp(List<LogicPurchaseReturnItemDO> pcsrmList, String pcsrId, boolean addOrUp)throws SyBaseException{
		if(addOrUp){
			for(LogicPurchaseReturnItemDO pcsrm : pcsrmList){
				if(pcsrm==null){
					continue;
				}else{
					if(StringUtils.isNotBlank(pcsrm.getId())){
						logicPurchaseReturnItemDAO.updateLogicPurchaseReturnItemDO(pcsrm);
					}else{
						pcsrm.setId(IDCodeTypeUtil.getId());
						pcsrm.setZd001ReturnId(pcsrId);
						logicPurchaseReturnItemDAO.insertLogicPurchaseReturnItemDO(pcsrm);
					}
				}
			}
		}else{
			for(LogicPurchaseReturnItemDO pcsrm : pcsrmList){
				if(pcsrm==null){
					continue;
				}
				pcsrm.setId(IDCodeTypeUtil.getId());
				pcsrm.setZd001ReturnId(pcsrId);
				logicPurchaseReturnItemDAO.insertLogicPurchaseReturnItemDO(pcsrm);
			}
		}
	}
	
	/**
	 * 根据当前的采购退货单的采购入库单id，查询所有的已退货单
	 * @param pcswId
	 */
	public Map<String, BigDecimal> findQueryPcsrItemToMap(String pcswId){
		Map<String, Object> pcsrMap = new HashMap<String, Object>();
		pcsrMap.put("pcswId", pcswId);
		pcsrMap.put("zdStatus", BillStatusUtil.PCSR_BILL_STATUS_FOUR);
		List<LogicPurchaseReturnItemDO> pcsrmList = logicPurchaseReturnItemDAO.findListByMap(pcsrMap);
		if(pcsrmList==null||pcsrmList.isEmpty()||pcsrmList.size()==0){
			return null;
		}else{
			Map<String, BigDecimal> pcsrmMap = new HashMap<String, BigDecimal>();
			for(LogicPurchaseReturnItemDO pcsrm : pcsrmList){
				if(pcsrm==null){
					continue;
				}
				String keyStr = pcswId+"_"+pcsrm.getZd003MaterId()+"_"+pcsrm.getZd008MaterModel()+"_"
							+pcsrm.getZd012MaterSize()+"_"+pcsrm.getZd010MaterColor()+"_"
							+pcsrm.getZd011MaterQuality();
				//每次退货数量
				BigDecimal backQuantity = pcsrm.getZd020BackQuantity()==null?BigDecimal.ZERO:pcsrm.getZd020BackQuantity();
				if(pcsrmMap.get(keyStr)==null){
					pcsrmMap.put(keyStr, backQuantity);
				}else{
					pcsrmMap.put(keyStr, backQuantity.add(pcsrmMap.get(keyStr)));
				}
			}
			return pcsrmMap;
		}
	}
	
	private Map<String, LogicPurchaseWareItemDO> findQuerayPcswmToMap(String pcswId){
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("pcswId", pcswId);
		List<LogicPurchaseWareItemDO> pcswmList =logicPurchaseWareItemDAO.findListByMap(paramMap);
		if(pcswmList==null||pcswmList.isEmpty()||pcswmList.size()==0){
			return null;
		}else{
			Map<String, LogicPurchaseWareItemDO> pcswmMap = new HashMap<String, LogicPurchaseWareItemDO>();
			for(LogicPurchaseWareItemDO pcswm : pcswmList){
				if(pcswm==null){
					continue;
				}
				String keyStr = pcswId + "_" + pcswm.getZd003MaterId()+"_"+pcswm.getZd007Model()+"_"
				+pcswm.getZd011Size()+"_"+pcswm.getZd009Color()+"_"+pcswm.getZd010Quality();
				pcswmMap.put(keyStr, pcswm);
			}
			return pcswmMap;
		}
	}
	
	@Override
	public LogicPurchaseReturnDO findListById(String id) throws SyBaseException {
		return logicPurchaseReturnDAO.findLogicPurchaseReturnDOByPrimaryKey(id);
	}

	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		return logicPurchaseReturnDAO.deleteBizRemoved(id);
	}

}
